﻿using System.Security.Cryptography;
using System.Text;
using Basic.HrCollect.Model;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Config;

namespace Basic.HrCollect.Config
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class HrEmpSignConfig : IHrEmpSignConfig
    {
        private string _Private;
        private string _Public;

        public string CertUpDir { get; private set; }

        public string CertName { get; private set; }

        public CertSource Source { get; private set; }

        public HrEmpSignConfig ( IConfigCollect config )
        {
            IConfigSection section = config.GetSection("HrSign");
            section.AddRefreshEvent(this._Init);
        }

        private void _Init ( IConfigSection section, string name )
        {
            this.CertUpDir = section.GetValue("CertUpDir", "EmpCertFile");
            this.CertName = section.GetValue("CertName", "WedonekSignCert");
            this.Source = section.GetValue<CertSource>("Source");
            string dir = section.GetValue("SignFileDir", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "signFile"));
            string path = Path.Combine(dir, "signPrivate.xml");
            if ( File.Exists(path) )
            {
                this._Private = Tools.ReadText(path, Encoding.UTF8, false);
            }
            path = Path.Combine(dir, "signPublic.xml");
            if ( File.Exists(path) )
            {
                this._Public = Tools.ReadText(path, Encoding.UTF8, false);
            }
        }

        public string Encryption ( string pwd )
        {
            using ( RSACryptoServiceProvider rsa = new RSACryptoServiceProvider() )
            {
                rsa.FromXmlString(this._Public);
                byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(pwd), false);
                return Convert.ToBase64String(bytes);
            }
        }
        public string Decrypt ( string pwd )
        {
            using ( RSACryptoServiceProvider rsa = new RSACryptoServiceProvider() )
            {
                rsa.FromXmlString(this._Private);
                byte[] bytes = rsa.Decrypt(Convert.FromBase64String(pwd), false);
                return Encoding.UTF8.GetString(bytes);
            }
        }
    }
}
